//
//  BuyerCommonListViewController.m
//  nonghubao
//
//  Created by Fenrir on 13-8-15.
//  Copyright (c) 2013年 Chongqing Nonghubao Co., Ltd. All rights reserved.
//

#import "BuyerCommonListViewController.h"
#import "Helper.h"
#import "Config.h"
#import "RTLabel.h"
#import "JMFBase.h"
#import "DynamicDetailViewController.h"
#import "ASImageView.h"
#import "MJRefresh.h"

@interface BuyerCommonListViewController ()<MJRefreshBaseViewDelegate>

@end

@implementation BuyerCommonListViewController
{
    MJRefreshFooterView *_footer;
    MJRefreshHeaderView *_header;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithStyle:(UITableViewStyle)style andCategory:(BuyerServiceCategory)category
{
    self = [super initWithStyle:style];
    
    if (self) {
        
        _category = category;
    }
    
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    UIButton *backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    if (_category == BuyerServiceCategoryFavorited) {
        
        self.title = _L(@"vc_title_073");
        
    }
    
    else if (_category == BuyerServiceCategoryBought) {
        self.title = _L(@"vc_title_074");
    }
    
    else {
        
    }
    
    _recordsDataSource = [NSMutableArray new];
    
    // 3.3行集成下拉刷新控件
    _header = [MJRefreshHeaderView header];
    _header.scrollView = self.tableView;
    _header.delegate = self;
    
    // 4.3行集成上拉加载更多控件
    _footer = [MJRefreshFooterView footer];
    _footer.delegate = self;
    
    // 5.0.5秒后自动下拉刷新
    [_header performSelector:@selector(beginRefreshing) withObject:nil afterDelay:0.5];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//    [self loadDataByCheckId:0];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return _recordsDataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.backgroundColor = [UIColor whiteColor];
        
        //商品图片
        
        ASImageView *imageView = [[ASImageView alloc] initWithFrame:CGRectMake(10.0f, 10.0f, 58.0f, 58.0f)];
        
        imageView.backgroundColor = [UIColor clearColor];
        
        [imageView.layer setMasksToBounds:YES];
        [imageView.layer setCornerRadius:6.0];
        [cell.contentView addSubview:imageView];
        
        //商品名称
        UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(imageView.frame.origin.x + imageView.frame.size.width + 10.0f, 5.0f, 200.0f, 25.0f)];
        nameLabel.font = _SYS_FONT_007;
        nameLabel.textColor = _SYS_COLOR_002;
        nameLabel.backgroundColor = [UIColor clearColor];
        
        [cell.contentView addSubview:nameLabel];
        
        //商品产地
        UILabel *regionLabel = [[UILabel alloc] initWithFrame:CGRectMake(imageView.frame.origin.x + imageView.frame.size.width + 10.0f, nameLabel.frame.origin.y + nameLabel.frame.size.height, 220.0f, 20.0f)];
        regionLabel.font = _SYS_FONT_005;
        regionLabel.textColor = _SYS_COLOR_002;
        regionLabel.backgroundColor = [UIColor clearColor];
        
        [cell.contentView addSubview:regionLabel];
        
        //商品价格
        RTLabel *priceLabel = [[RTLabel alloc] initWithFrame:CGRectMake(imageView.frame.origin.x + imageView.frame.size.width + 10.0f, regionLabel.frame.origin.y + regionLabel.frame.size.height, 200.0f, 25.0f)];
        priceLabel.font = _SYS_FONT_005;
        priceLabel.backgroundColor = [UIColor clearColor];
        
        [cell.contentView addSubview:priceLabel];
    }
    
    //获得次cell应该被填充的数据
    NSDictionary *dataForCell = [_recordsDataSource objectAtIndex:indexPath.row];
    
    //获得cell的子views
    NSArray *views = [cell.contentView subviews];
    
    ASImageView *imageView = [views objectAtIndex:0];
    UILabel *nameLabel = [views objectAtIndex:1];
    UILabel *regionLabel = [views objectAtIndex:2];
    RTLabel *priceLabel = [views objectAtIndex:3];
    
    NSURL* previewAvatarURL = [NSURL URLWithString:dataForCell[@"picturePreview"]];
    [imageView setImageURL:previewAvatarURL andSourceImageURL:nil forStyle:PictureStyleNormalPreview];
    nameLabel.text = dataForCell[@"name"];
    regionLabel.text = [NSString stringWithFormat:_L(@"tpl_46"), dataForCell[@"provenance"]];
    priceLabel.text = [NSString stringWithFormat:_L(@"tpl_40"), [dataForCell[@"price"] floatValue]];
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80.0f;
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

- (UITableViewCellEditingStyle )tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return UITableViewCellEditingStyleDelete;
}

 // Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
     
        JSONRequest* request;
        
     if (_category == BuyerServiceCategoryFavorited) {
         
         request = [[JSONRequest alloc] initWithURLString:_JSON_URL_PRODUCT_PRODUCT_COLLECT_REMOVE];
         [request setValue:_recordsDataSource[indexPath.row][@"id"] forParameter:@"collectIds"];
         NSDictionary* dict = [request synchronous];
         JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
         if (jmf.status == JMStatusSucceed) {
             
             [_recordsDataSource removeObjectAtIndex:indexPath.section];
             
             // Delete the row from the data source
             [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
             
             [Helper showAllTextDialog:_L(@"alert_100") inSeconds:1.5f];
            
         }
         else {
             [Helper easyShowJMFStatus:jmf];
         }

     }
     
     else {
         
     }
    
    if (_recordsDataSource.count == 0) {
        
        [self.tableView reloadData];
    }
 }

}

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DynamicDetailViewController *trendDetailVC = [[DynamicDetailViewController alloc] initWithID:[_recordsDataSource[indexPath.row][@"dynamicId"] integerValue]];
    [self.navigationController pushViewController:trendDetailVC animated:YES];
}

#pragma mark - 私有方法

- (void)loadDataByCheckId:(NSInteger)checkId
{
    
    JSONRequest* request;
    
    if (_category == BuyerServiceCategoryBought) {
        request = [[JSONRequest alloc] initWithURLString:_JSON_URL_PRODUCT_PRODUCT_BUY_LIST];
    }
    else if (_category == BuyerServiceCategoryFavorited) {
        request = [[JSONRequest alloc] initWithURLString:_JSON_URL_PRODUCT_PRODUCT_COLLECT_LIST];
    }
    else {
        
    }
    request.delegate = self;
    
    //id不为空，说明用户在加载更多
    if(checkId != 0){
        
        [request setValue:[NSNumber numberWithInteger:checkId] forParameter:@"checkId"];
        
        [request setSuccessSelector:@selector(moreDataDidReceived:)];
    }
    
    [request asynchronous];
}

- (NSInteger)catchTheLastDataSourceId
{
    if (_recordsDataSource.count != 0) {
        return [_recordsDataSource[_recordsDataSource.count - 1][@"id"] integerValue];
    }
    else{
        return 0;
    }
}


- (void)viewNeedsDisplay
{
    
//    [self rightButtonNeedsDisplay];
    
    if (_recordsDataSource.count == 0) {
        
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        _blankPage = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, _SYS_FRAME_HEIGHT-44.0f)];
        _blankPage.backgroundColor = [UIColor whiteColor];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 139/2.0f, 137.0f/2.0f)];
        
        if (_category == BuyerServiceCategoryBought) {
            imageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_img_015@2x" ofType:@"png"]];
        }
        else if (_category == BuyerServiceCategoryFavorited) {
            imageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_img_014@2x" ofType:@"png"]];
        }
        else {
            
        }
        
        imageView.center = _blankPage.center;
        [_blankPage addSubview:imageView];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, imageView.frame.origin.y+imageView.frame.size.height+10.0f, 300.0f, 20.0f)];
        label.textAlignment = UITextAlignmentCenter;
        label.numberOfLines = 0;
        label.textColor = [UIColor grayColor];
        
        if (_category == BuyerServiceCategoryBought) {
            label.text = _L(@"alert_105");
        }
        else if (_category == BuyerServiceCategoryFavorited) {
            label.text = _L(@"alert_106");
            
            self.navigationItem.rightBarButtonItem = nil;
        }
        else {
            
        }
        
        [_blankPage addSubview:label];
        
        [self.view addSubview:_blankPage];
        
    }else{
        
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        
        if (_category == BuyerServiceCategoryFavorited) {
            //导航按钮右按钮：编辑
            UIButton* editButton = [Helper buttonWithStyle:ButtonStyleNavigationEdit];
            [editButton addTarget:self action:@selector(editButtonEvent) forControlEvents:UIControlEventTouchUpInside];
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:editButton];
        }
        
        [_blankPage removeFromSuperview];
        
    }
}

//刷新tableview
- (void)reloadTableView
{
    [self.tableView reloadData];
    // 结束刷新状态
    [_header endRefreshing];
    [_footer endRefreshing];
}

#pragma mark - 自定义事件

/*!
 @abstract 返回按钮事件
 */
- (void)backButtonEvent:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

/*!
 @abstract 添加按钮事件
 */
- (void)editButtonEvent
{
    [self.tableView setEditing:!self.tableView.editing animated:YES];
    
    if (self.tableView.editing) {
        UIButton *addButton = [Helper buttonWithStyle:ButtonStyleNavigationDone];
        [addButton addTarget:self action:@selector(editButtonEvent) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:addButton];
    }
    else {
        UIButton* editButton = [Helper buttonWithStyle:ButtonStyleNavigationEdit];
        [editButton addTarget:self action:@selector(editButtonEvent) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:editButton];
    }
}

#pragma mark - JSONRequestDelegate

//
- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        if (_recordsDataSource.count != 0) {
            [_recordsDataSource removeAllObjects];
        }
        
        //将每次下拉刷新出的新数据都加入到数据源的最前面
        if ([(NSArray *)jmf.data count] != 0) {
            
            [_recordsDataSource addObjectsFromArray:(NSArray *)jmf.data];
            
            _footer.scrollView = self.tableView;
        }
        
        if (_recordsDataSource.count > 0) {
            self.tableView.tableFooterView.hidden = NO;
        }
        else {
            self.tableView.tableFooterView.hidden = YES;
        }
        
        [self reloadTableView];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
    
    
    [self viewNeedsDisplay];
}

- (void)moreDataDidReceived:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        if ([(NSArray *)jmf.data count] != 0) {
            self.tableView.tableFooterView.hidden = NO;
            [_recordsDataSource addObjectsFromArray:(NSArray *)jmf.data];
            
        }
        else{
            self.tableView.tableFooterView.hidden = YES;
        }
        [self reloadTableView];
    }
    else {
        
        [Helper easyShowJMFStatus:jmf];
    }
}

//
- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}

#pragma mark - 刷新的代理方法---进入下拉刷新\上拉加载更多都有可能调用这个方法
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    //下拉刷新
    if (refreshView == _header) {
        
        //请求初始数据
        [self loadDataByCheckId:0];
    }
    
    //上拉加载更多
    else {
        
        if ([self catchTheLastDataSourceId] != 0) {
            [self loadDataByCheckId:[self catchTheLastDataSourceId]];
        }
    }
}

@end
